let stompClient = null;
let currentUser = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 检查是否已登录
    const savedUser = localStorage.getItem('currentUser');
    if (savedUser) {
        currentUser = JSON.parse(savedUser);
        showChatInterface();
        connectWebSocket();
    }
    
    // 绑定登录表单事件
    document.getElementById('loginFormElement').addEventListener('submit', handleLogin);
    
    // 绑定消息输入框回车事件
    document.getElementById('messageInput').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            sendMessage();
        }
    });
});

// 处理登录
async function handleLogin(e) {
    e.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const nickname = document.getElementById('nickname').value;
    
    try {
        const response = await fetch('/api/user/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username, password })
        });
        
        const data = await response.json();
        
        if (data.success) {
            currentUser = data.user;
            currentUser.nickname = nickname; // 使用用户输入的昵称
            localStorage.setItem('currentUser', JSON.stringify(currentUser));
            showChatInterface();
            connectWebSocket();
        } else {
            alert(data.message);
        }
    } catch (error) {
        console.error('登录失败:', error);
        alert('登录失败，请重试');
    }
}

// 显示注册表单
function showRegisterForm() {
    const loginBtn = document.querySelector('button[type="submit"]');
    const registerBtn = document.querySelector('button[onclick="showRegisterForm()"]');
    
    if (loginBtn.textContent === '登录') {
        loginBtn.textContent = '注册';
        registerBtn.textContent = '返回登录';
        document.getElementById('loginFormElement').onsubmit = handleRegister;
    } else {
        loginBtn.textContent = '登录';
        registerBtn.textContent = '注册';
        document.getElementById('loginFormElement').onsubmit = handleLogin;
    }
}

// 处理注册
async function handleRegister(e) {
    e.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const nickname = document.getElementById('nickname').value;
    
    try {
        const response = await fetch('/api/user/register', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username, password, nickname })
        });
        
        const data = await response.json();
        
        if (data.success) {
            alert('注册成功，请登录');
            showRegisterForm(); // 切换回登录模式
        } else {
            alert(data.message);
        }
    } catch (error) {
        console.error('注册失败:', error);
        alert('注册失败，请重试');
    }
}

// 显示聊天界面
function showChatInterface() {
    document.getElementById('loginForm').classList.add('hidden');
    document.getElementById('chatInterface').classList.remove('hidden');
    document.getElementById('currentUser').textContent = currentUser.nickname;
    
    // 加载在线用户列表
    loadOnlineUsers();
}

// 连接WebSocket
function connectWebSocket() {
    const socket = new SockJS('/ws');
    stompClient = Stomp.over(socket);
    
    stompClient.connect({}, function(frame) {
        console.log('Connected: ' + frame);
        
        // 订阅公共消息
        stompClient.subscribe('/topic/public', function(message) {
            showMessage(JSON.parse(message.body));
        });
        
        // 订阅私聊消息
        stompClient.subscribe('/user/queue/private', function(message) {
            showMessage(JSON.parse(message.body));
        });
        
        // 发送用户加入消息
        stompClient.send("/app/chat.addUser", {}, JSON.stringify({
            sender: currentUser.username,
            senderNickname: currentUser.nickname,
            type: 'JOIN'
        }));
    });
}

// 发送消息
function sendMessage() {
    const messageInput = document.getElementById('messageInput');
    const messageContent = messageInput.value.trim();
    
    if (messageContent && stompClient) {
        const chatMessage = {
            sender: currentUser.username,
            senderNickname: currentUser.nickname,
            content: messageContent,
            type: 'MESSAGE',
            messageType: 'TEXT',
            roomId: 'public'
        };
        
        stompClient.send("/app/chat.sendMessage", {}, JSON.stringify(chatMessage));
        messageInput.value = '';
    }
}

// 显示消息
function showMessage(message) {
    const messageArea = document.getElementById('messageArea');
    const messageElement = document.createElement('div');
    
    let messageClass = 'message other';
    let messageContent = '';
    
    if (message.type === 'JOIN' || message.type === 'LEAVE') {
        messageClass = 'message system';
        messageContent = message.content;
    } else if (message.sender === currentUser.username) {
        messageClass = 'message own';
        messageContent = `<strong>${message.senderNickname}</strong>: ${message.content}`;
    } else {
        messageContent = `<strong>${message.senderNickname}</strong>: ${message.content}`;
    }
    
    messageElement.className = messageClass;
    messageElement.innerHTML = messageContent;
    messageArea.appendChild(messageElement);
    
    // 滚动到底部
    messageArea.scrollTop = messageArea.scrollHeight;
}

// 加载在线用户列表
async function loadOnlineUsers() {
    try {
        const response = await fetch('/api/users/online');
        const users = await response.json();
        
        const usersList = document.getElementById('onlineUsersList');
        const onlineCount = document.getElementById('onlineCount');
        
        usersList.innerHTML = '';
        onlineCount.textContent = users.length;
        
        users.forEach(user => {
            const userElement = document.createElement('div');
            userElement.className = 'user-item online';
            userElement.innerHTML = `
                <i class="fas fa-circle text-success me-2"></i>
                ${user.nickname}
            `;
            usersList.appendChild(userElement);
        });
    } catch (error) {
        console.error('加载在线用户失败:', error);
    }
}

// 退出登录
async function logout() {
    if (stompClient) {
        stompClient.disconnect();
    }
    
    try {
        await fetch('/api/user/logout', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ userId: currentUser.id })
        });
    } catch (error) {
        console.error('退出失败:', error);
    }
    
    localStorage.removeItem('currentUser');
    currentUser = null;
    
    document.getElementById('chatInterface').classList.add('hidden');
    document.getElementById('loginForm').classList.remove('hidden');
    document.getElementById('loginFormElement').reset();
}

// 定期刷新在线用户列表
setInterval(loadOnlineUsers, 5000); 